<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Excel文件翻译</title>
    <style>
        /* 简单的样式 */
        table {
            width: 100%; /* 表格宽度 */
            border-collapse: collapse; /* 合并相邻的边框 */
            margin-bottom: 20px; /* 底部外边距 */
        }

        /* 表格头部样式 */
        th {
            background-color: #f2f2f2; /* 背景色 */
            text-align: left; /* 文本左对齐 */
            padding: 10px; /* 内边距 */
            border: 1px solid #ddd; /* 边框 */
        }

        /* 表格主体样式 */
        td {
            padding: 10px; /* 内边距 */
            border: 1px solid #ddd; /* 边框 */
        }

        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }

        input[type="file"] {
            margin-bottom: 10px;
        }

        select {
            margin-bottom: 10px;
        }

        #result {
            margin-top: 20px;
            border: 1px solid #ccc;
            padding: 10px;
            height: 200px;
            overflow: auto;
        }

        .copy-container {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        .copy-button {
            margin-left: 10px;
            padding: 5px 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
        }

        .copy-button:hover {
            background-color: #45a049;
        }

        .flex-container {
            display: flex;
            justify-content: space-between;
            align-items: center; /* 如果需要的话，可以垂直居中 */
        }

        /* 按钮样式 */
        button {
            padding: 5px 10px; /* 内边距 */
            background-color: #4CAF50; /* 背景色 */
            color: white; /* 文本颜色 */
            border: none; /* 无边框 */
            cursor: pointer; /* 鼠标指针样式 */
        }

        button:hover {
            background-color: #45a049; /* 鼠标悬停时的背景色 */
        }

        textarea {
            width: 100%;
            height: 100px;
            resize: vertical; /* 允许垂直缩放 */
            font-size: 16px; /* 字体大小 */
            font-family: Arial, sans-serif; /* 字体 */
            padding: 10px; /* 内边距 */
            border: 1px solid #ccc; /* 边框 */
            box-sizing: border-box; /* 盒模型 */
            margin: 10px;
            outline: none; /* 去除轮廓 */
            background-color: #f5f5f5; /* 背景色 */
            border-radius: 5px; /* 圆角边框 */
            transition: all 0.3s ease-in-out; /* 过渡效果 */
            color: #333; /* 文本颜色 */
            font-weight: 400; /* 字体粗细 */
            letter-spacing: 1px; /* 字间距 */
            line-height: 1.5; /* 行高 */
            text-align: left; /* 文本对齐 */
            white-space: pre; /* 保留空格 */
            overflow-wrap: break-word; /* 溢出换行 */
            font-style: normal; /* 字体样式 */
            font-variant: normal; /* 字体变体 */
            --background-color: #f5f5f5; /* 背景色 */
            --border-color: #ccc; /* 边框颜色 */
        }

    </style>
</head>
<body>
<h1>飞书云盘获取文档链接</h1>
<form id="feishu" action="/feishu" method="post">
    <label for="text">请输入html代码（f12-右键body元素-复制-复制元素）: </label>
    <textarea name="text" id="text" cols="30" rows="10"></textarea>

    重设: <input type="reset" value="Reset">
    提交: <input type="submit" value="Submit">
</form>
<h1>Excel文件翻译</h1>
<input type="file" id="fileInput" accept=".xlsx, .xls">

<span>
    <button id="translateButton">翻译</button>
    <br>
    <!--    <button onclick="addTextArea()">Add TextArea</button>-->
    <!--    <button onclick="addLanguage()">Add Language</button>-->
</span>
<form id="myForm" action="/table" method="post">
    <!--    <div id="language"></div>-->
    <!--    <div id="text"></div>-->
    <label>
        text:
        <textarea name="text"></textarea>
    </label>
    <br>
    重设: <input type="reset" value="Reset">
    提交: <input type="submit" value="Submit">

</form>
<div id="result" style="display: table; width: 100%;">

</div>


<button id="btn">复制</button>
<script>


    function showdata(data) {
        //debugger;
        data = Object.values(data)[0];
        let resultDiv = document.getElementById('result');
        const table = document.createElement('table');
        table.style.width = '100%';
        table.style.height = 'auto';
        table.style.borderCollapse = 'collapse';
        table.setAttribute("id", "table");
        const thead = document.createElement('thead');
        const tbody = document.createElement('tbody');
        tbody.setAttribute("id", "tbody");
        table.appendChild(thead);
        table.appendChild(tbody);
        // 表头渲染
        for (let i = 0; i < data[0].length; i++) {
            const th = document.createElement('th');
            th.textContent = data[0][i] + "\t";
            thead.appendChild(th);
        }

        //内容渲染
        for (let i = 1; i < data.length; i++) {
            let tr = document.createElement('tr');
            for (let j = 0; j < data[i].length; j++) {
                let td = document.createElement('td');
                let span = document.createElement('span');
                span.textContent = data[i][j] + "\t";
                td.appendChild(span);
                tr.appendChild(td);
            }
            tbody.appendChild(tr);
        }

        resultDiv.innerHTML = ''; // 清空结果区域
        resultDiv.appendChild(table); // 将表格添加到页面中
    }

    document.getElementById('feishu').addEventListener('submit', function (e) {
        e.preventDefault(); // 阻止表单的默认提交行为
        let html = document.getElementsByTagName('textarea')[0].value
        if (!text) {
            alert('请输入要翻译的文本！');
            return;
        }
        let formData = new FormData();
        formData.append('text', html);
        fetch('/feishu', {
            method: 'POST',
            body: formData,
        }).then(async function (response) {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const data = await response.json();
            debugger;
            text = data.text;
            copyToClip(text);
        }).then(function (data) {
            console.log(data);
        }).catch(function (error) {
            console.error('There has been a problem with your fetch operation:', error);
            alert(error);
        });
    });
    document.getElementById('myForm').addEventListener('submit', function (e) {
        e.preventDefault(); // 阻止表单的默认提交行为
        // // 开启调试
        // debugger;
        // let selects = document.getElementsByTagName('select');
        let text = document.getElementsByTagName('textarea')[1].value
        if (!text) {
            alert('请输入要翻译的文本！');
            return;
        }
        let formData = new FormData();
        formData.append('text', text);
        // // 收集首行（表头）数据
        // // rows[0].getElementsByTagName('select')[0].value
        // let languages = [];
        // for (let i = 0; i < selects.length; i++) {
        //     languages.push(selects[i].value);
        // }
        // // 收集首行（表头）数据
        // let textareas = document.getElementsByTagName('textarea');
        // let text = [];
        // for (let i = 0; i < textareas.length; i++) {
        //     text.push(textareas[i].value);
        // }
        //
        // languages.forEach((value, index) => {
        //     formData.append(`languages`, value)
        // })
        //
        // text.forEach((value, index) => {
        //     formData.append(`text`, value)
        // })

        // console.log(formData);
        // 使用fetch API提交表单数据
        fetch('/table', {
            method: 'POST',
            body: formData,
            // headers: {
            //     'Content-Type': 'multipart/form-data;boundary=----WebKitFormBoundary7H0513Kj264Q89'
            // }
        }).then(async function (response) {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const data = await response.json();
            showdata(data);
        }).then(function (data) {
            console.log(data);
        }).catch(function (error) {
            console.error('There has been a problem with your fetch operation:', error);
            alert(error);
        });

    });


    function addTextArea() {
        let div = document.getElementById("text");
        // 创建一个<textarea>元素，并将其添加到cell中
        let input = document.createElement("textarea");
        div.appendChild(input);
    }

    function addLanguage() {
        let div = document.getElementById("language");
        // 创建一个新的<select>元素
        let select = document.createElement("select");
        // 创建几个<option>元素并添加到<select>中
        let options = {
            "cht": "中文(繁体)",
            "ru": "俄语",
            "tr": "土耳其语",
            "th": "泰语",
            "it": "意大利语",
            "id": "印尼语",
            "vie": "越南语",
            "spa": "西班牙语",
            "kor": "韩语",
            "jp": "日语",
            "pt": "葡萄牙语",
            "de": "德语",
            "fra": "法语",
        };
        for (let i = 0; i < Object.keys(options).length; i++) {
            let option = document.createElement("option");
            option.value = Object.keys(options)[i];
            option.text = Object.values(options)[i];
            select.appendChild(option);
        }
        // 找到目标cell元素并将<select>添加到其中
        div.appendChild(select);
    }

    function createTextAndCopyButton(text) {
        // 创建一个td元素
        let td = document.createElement('td');

        // 创建一个包含文本和按钮的flex容器
        let flexContainer = document.createElement('div');
        flexContainer.className = 'flex-container';

        // 创建一个span元素用于显示文本
        let span = document.createElement('span');
        span.textContent = text + "\t\t";
        flexContainer.appendChild(span);


        td.appendChild(flexContainer);

        return td;
    }


    /**
     * 复制多行内容到粘贴板
     * contentArray: 需要复制的内容（传一个字符串数组）
     * message : 复制完后的提示，不传则默认提示"复制成功"
     */
    function copyToClip(contentArray, message) {
        const textarea = document.createElement('textarea');
        textarea.value = contentArray;
        document.body.appendChild(textarea);
        textarea.select();
        if (document.execCommand('copy')) {
            document.execCommand('copy');
        }
        document.body.removeChild(textarea);
        if (message == null) {
            alert("复制成功");
        } else {
            alert(message);
        }
    }


    document.getElementById('btn').onclick = function () {
        let table = document.getElementById('table'); // 确保这里选择的是<tbody>元素，而不是整个<table>
        let trs = table.getElementsByTagName('tr');
        let textToCopy = '';
        for (let i = 0; i < trs.length; i++) {
            let spans = trs[i].getElementsByTagName('span');
            for (let j = 0; j < spans.length; j++) {
                textToCopy += spans[j].textContent;
            }
            //去除最后一个/t
            textToCopy = textToCopy.substring(0, textToCopy.length - 1);
            textToCopy += '\n';
        }
        console.log(textToCopy);
        copyToClip(textToCopy);
    };


    document.getElementById('translateButton').addEventListener('click', async function () {
        let fileInput = document.getElementById('fileInput');
        let resultDiv = document.getElementById('result');
        let file = fileInput.files[0];
        const table = document.createElement('table');
        table.style.width = '100%';
        table.style.height = 'auto';
        table.style.borderCollapse = 'collapse';
        table.setAttribute("id", "table");

        if (!file) {
            alert('请选择要上传的Excel文件！');
            return;
        }

        let formData = new FormData();
        formData.append('file', file);

        try {
            const response = await fetch('/upload', { // 假设后端接口是/upload
                body: formData,
                method: 'POST',
            });
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const data = await response.json();
            showdata(data);
        } catch (error) {
            console.error('There has been a problem with your fetch operation:', error);
            alert(error);
        }

    });
</script>
</body>
</html>